package com.myflink.day03;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @author Shelly An
 * @create 2020/9/18 10:38
 */
public class Operator_Reduce {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        DataStreamSource<String> fileDS = env.socketTextStream("localhost", 4444);
        SingleOutputStreamOperator<Tuple3<String, Long, Integer>> sensorDS = fileDS.map(new MapFunction<String, Tuple3<String, Long, Integer>>() {

            @Override
            public Tuple3<String, Long, Integer> map(String value) throws Exception {
                String[] datas = value.split(",");
                //开发中，用包装类多一些。 parse返回的是基本类型
                return new Tuple3<>(datas[0], Long.valueOf(datas[1]), Integer.valueOf(datas[2]));
            }
        });

        KeyedStream<Tuple3<String, Long, Integer>, String> sensorKS = sensorDS.keyBy(r -> r.f0);

        // 1. 输入类型要一致，输出类型也要一致
        // 2. 第一条来的数据不会进入reduce
        // 3. 帮用户保存了中间状态
        SingleOutputStreamOperator<Tuple3<String, Long, Integer>> result = sensorKS.reduce(new ReduceFunction<Tuple3<String, Long, Integer>>() {
            @Override
            public Tuple3<String, Long, Integer> reduce(Tuple3<String, Long, Integer> value1, Tuple3<String, Long, Integer> value2) throws Exception {
                System.out.println("进入reduce方法：" + value1.toString() + " reduce " + value2.toString());
                return Tuple3.of(value1.f0 + "-" + value2.f0, System.currentTimeMillis(), Math.max(value1.f2, value2.f2));
            }
        });

        result.print("reduce");

        env.execute();
    }
}
